package com.binguo.service;

import com.alibaba.fastjson.JSONObject;
import com.binguo.common.enums.CardType;
import com.binguo.common.enums.ProductStorageType;
import com.binguo.common.exception.ServiceException;
import com.binguo.common.util.PriceUtil;
import com.binguo.entity.ProductVO;
import com.binguo.helper.FaceHelperV3;
import com.binguo.model.mapper.*;
import com.binguo.model.model.*;
import com.binguo.model.repository.*;
import com.binguo.model.wxapi.form.ApiCreateShopForm;
import com.binguo.model.wxapi.result.ShopAPIResult;
import com.binguo.model.wxapi.vo.ShopVO;
import com.binguo.thirdPay.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.binguo.common.exception.ErrorCode.*;


/**
 *
 */
@Service
public class ShopService {
    private static final Logger logger = LoggerFactory.getLogger(ShopService.class);
    @Autowired
    ShopRepository shopRepository;
    @Resource
    ShopOnlineMealMapper shopOnlineMealMapper;
    @Autowired
    ShopConfigExtendRepository shopConfigExtendRepository;

    @Autowired
    CmsRoleRepository cmsRoleRepository;

    @Autowired
    CmsSysUserRepository cmsSysUserRepository;

    @Resource
    CmsSysUserRoleMapper cmsSysUserRoleMapper;

    @Autowired
    ShopBaiduUrlRepository shopBaiduUrlRepository;

    @Autowired
    ShopChannelRepository shopChannelRepository;

    @Autowired
    ShopTempRepository shopTempRepository;

    @Autowired
    ProductCategoryRepository productCategoryRepository;


    @Resource
    BranchMapper branchMapper;

    @Resource
    LogProductImgMapper logProductImgMapper;

    @Resource
    PayCardMapper payCardMapper;

    @Resource
    ProductMapper productMapper;
    @Resource
    ProductInventoryMapper productInventoryMapper;
    @Resource
    ShopBaiduUrlCurMapper shopBaiduUrlCurMapper;
    @Autowired
    ShopCaogenyaoConfigRepository shopCaogenyaoConfigRepository;
    @Resource
    ShopMapper shopMapper;
    @Autowired
    CustomerGroupRepository customerGroupRepository;
    @Resource
    CustomerExtendMapper customerExtendMapper;
    @Resource
    ShopConfigRepository shopConfigRepository;

    static String img = "https://binguoai.com/noimg.jpeg";
    static List<String> imgList = new ArrayList<>();

    static {
        imgList.add(img);
    }


    public Map<String, Object> getMeshProductList(Integer branchId) {
        Condition condition = new Condition(Product.class);

        condition.or().andEqualTo("storeid", branchId)
                .andEqualTo("status", 1)
                .andEqualTo("productType", 2)
                .andEqualTo("deleted", false)
        ;

        List<Product> productList = productMapper.selectByCondition(condition);

        if (productList != null && productList.size() > 0) {
            List<Integer> productIdList = productList.stream().map(Product::getId).collect(Collectors.toList());

            Condition productStorageCondition = new Condition(ProductInventory.class);
            productStorageCondition.or().andIn("productId", productIdList);
            List<ProductInventory> productInventoryList = productInventoryMapper.selectByCondition(productStorageCondition);

            Map<Integer, ProductInventory> productInventoryMap =
                    productInventoryList.stream().collect(Collectors.toMap(ProductInventory::getProductId, p -> p));


            Condition productImgCondition = new Condition(LogProductImg.class);
            productImgCondition.or().andIn("productId", productIdList);
            List<LogProductImg> logProductImgList = logProductImgMapper.selectByCondition(productImgCondition);

            Map<Integer, List<String>> productImgListMap = null;
            if (logProductImgList != null && logProductImgList.size() > 0) {
                productImgListMap = new HashMap<>();

                for (LogProductImg logProductImg : logProductImgList) {
                    List<String> imgList = productImgListMap.get(logProductImg.getProductId());

                    if (imgList == null) {
                        imgList = new ArrayList<>();
                        productImgListMap.put(logProductImg.getProductId(), imgList);
                    }

                    imgList.add(logProductImg.getSourceImg());
                }
            }


            List<ProductVO> breakfastList = new ArrayList<>();
            List<ProductVO> lunchList = new ArrayList<>();
            List<ProductVO> dinnerList = new ArrayList<>();

            for (Product product : productList) {

                ProductInventory temp = productInventoryMap.get(product.getId());

                if (temp == null) {
                    continue;
                }

                if (temp.getBreakfastGeneralSum() == ProductStorageType.Limited.getCode()
                        || temp.getBreakfastGeneralSum() == ProductStorageType.NoLimited.getCode()
                ) {

                    ProductVO productVO = copyProp(product, temp);
                    List<String> picList = null;
                    if (productImgListMap != null) {
                        picList = productImgListMap.get(productVO.getId());
                    }

                    if (picList != null && picList.size() > 0) {
                        productVO.setPicList(picList);
                        productVO.setProductPic(picList.get(0));
                    } else {
                        productVO.setPicList(imgList);
                        productVO.setProductPic(img);
                    }


                    if (temp.getBreakfastGeneralSum() == ProductStorageType.NoLimited.getCode()) {
                        productVO.setRemains(100);
                    } else {
                        productVO.setRemains(temp.getBraekfastSum());
                    }
                    productVO.setShow(temp.getBreakfastGeneralSum());

                    breakfastList.add(productVO);
                }

                if (temp.getLunchGeneralSum() == ProductStorageType.Limited.getCode()
                        || temp.getLunchGeneralSum() == ProductStorageType.NoLimited.getCode()
                ) {

                    ProductVO productVO = copyProp(product, temp);
                    List<String> picList = null;
                    if (productImgListMap != null) {
                        picList = productImgListMap.get(productVO.getId());
                    }

                    if (picList != null && picList.size() > 0) {
                        productVO.setPicList(picList);
                        productVO.setProductPic(picList.get(0));
                    } else {
                        productVO.setPicList(imgList);
                        productVO.setProductPic(img);
                    }

                    if (temp.getLunchGeneralSum() == ProductStorageType.NoLimited.getCode()) {
                        productVO.setRemains(100);
                    } else {
                        productVO.setRemains(temp.getLunchSum());
                    }

                    productVO.setShow(temp.getLunchGeneralSum());

                    lunchList.add(productVO);
                }

                if (temp.getDinnerGeneralSum() == ProductStorageType.Limited.getCode()
                        || temp.getDinnerGeneralSum() == ProductStorageType.NoLimited.getCode()
                ) {
                    ProductVO productVO = copyProp(product, temp);
                    List<String> picList = null;
                    if (productImgListMap != null) {
                        picList = productImgListMap.get(productVO.getId());
                    }

                    if (picList != null && picList.size() > 0) {
                        productVO.setPicList(picList);
                        productVO.setProductPic(picList.get(0));
                    } else {
                        productVO.setPicList(imgList);
                        productVO.setProductPic(img);
                    }

                    if (temp.getDinnerGeneralSum() == ProductStorageType.NoLimited.getCode()) {
                        productVO.setRemains(100);
                    } else {
                        productVO.setRemains(temp.getDinnerSum());
                    }

                    productVO.setShow(temp.getDinnerGeneralSum());

                    dinnerList.add(productVO);

                }
            }

            Map<String, Object> result = new HashMap<>();

            if (breakfastList.size() > 0) {
                result.put("breakfast", breakfastList);
            }
            if (lunchList.size() > 0) {
                result.put("lunch", lunchList);
            }
            if (dinnerList.size() > 0) {
                result.put("dinner", dinnerList);
            }

            return result;
        }

        return null;
    }

    private ProductVO copyProp(Product product, ProductInventory productInventory) {
        return ProductVO.builder()
                .id(product.getId())
                .name(product.getName())
                .productPic(product.getProductpic())
                .searchCode(product.getSearchcode())
                .standard(productInventory.getStandard())
                .price(PriceUtil.changeF2Y(product.getPrice()).replaceAll(",", ""))
                .build()
                ;
    }

    public List<ShopVO> getMeshShopList(Integer customerId) {
        Condition condition = new Condition(PayCard.class);
        condition.or().andEqualTo("customerid", customerId)
                .andEqualTo("deleted", false)
        ;
        List<PayCard> payCardList = payCardMapper.selectByCondition(condition);

        if (payCardList != null && payCardList.size() > 0) {
            List<Integer> shopIdList = new ArrayList<>();
            payCardList.stream().forEach(payCard -> {
                if (!shopIdList.contains(payCard.getShopid())) {
                    shopIdList.add(payCard.getShopid());
                }
            });

            String shopIdListStr = org.apache.commons.lang3.StringUtils.join(shopIdList.toArray(), ",");

            List<Shop> shopList = shopRepository.findByIds(shopIdListStr);

            List<ShopVO> items = new ArrayList<>();

            Map<Integer, String> shopIdNameMap = shopList.stream().collect(Collectors.toMap(Shop::getId, Shop::getName));

            Condition shopMealCondition = new Condition(ShopOnlineMeal.class);
            shopMealCondition.or().andIn("shopId", shopIdList);
            List<ShopOnlineMeal> shopOnlineMealList =
                    shopOnlineMealMapper.selectByCondition(shopMealCondition);

            if (shopOnlineMealList != null && shopOnlineMealList.size() > 0) {
                shopOnlineMealList.stream().forEach(shopOnlineMeal -> {
                    items.add(ShopVO.builder()
                            .shopId(shopOnlineMeal.getShopId())
                            .shopName(shopIdNameMap.get(shopOnlineMeal.getShopId()))
                            .build());
                });
            }
            return items;
        } else {
            return null;
        }

    }

    public List<Branch> getBranchList(Integer shopId) {
        Condition condition = new Condition(Branch.class);
        condition.or().andEqualTo("shopId", shopId);
        List<Branch> branchList = branchMapper.selectByCondition(condition);

        if (branchList != null && branchList.size() > 0) {
            return branchList;
        } else {
            Shop shop = shopRepository.findById(shopId);
            Branch branch = new Branch();
            branch.setBranchName(shop.getName());
            branch.setShopId(shopId);

            branchMapper.insertSelective(branch);

            branchList = new ArrayList<>();
            branchList.add(branch);
            return branchList;
        }
    }


    public ShopOnlineMeal shopMeshConfig(Integer shopId, Integer autoConfig,
                                         Integer breakfastStatus, Integer lunchStatus, Integer dinnerStatus
    ) {
        Condition condition = new Condition(ShopOnlineMeal.class);
        condition.or().andEqualTo("shopId", shopId);

        List<ShopOnlineMeal> shopOnlineMealList = shopOnlineMealMapper.selectByCondition(condition);
        if (shopOnlineMealList != null && shopOnlineMealList.size() > 0) {
            ShopOnlineMeal shopOnlineMeal = shopOnlineMealList.get(0);

            ShopOnlineMeal temp = new ShopOnlineMeal();
            temp.setId(shopOnlineMeal.getId());
            temp.setIsAutoConfig(autoConfig);

            if (autoConfig == 1) {
                int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
                if (hour >= 10 && hour < 15) {//中餐
                    temp.setBreakfastStatus(0);
                    temp.setLunchStatus(1);
                    temp.setDinnerStatus(0);
                } else if (hour >= 15) {//晚餐
                    temp.setBreakfastStatus(0);
                    temp.setLunchStatus(0);
                    temp.setDinnerStatus(1);
                } else {//早餐
                    temp.setBreakfastStatus(1);
                    temp.setLunchStatus(0);
                    temp.setDinnerStatus(0);
                }
            } else {
                temp.setBreakfastStatus(breakfastStatus);
                temp.setLunchStatus(lunchStatus);
                temp.setDinnerStatus(dinnerStatus);
            }
            shopOnlineMealMapper.updateByPrimaryKeySelective(temp);

            return temp;
        } else {
            return null;
        }
    }

    public void checkPhone(String phone) {
        Condition condition = new Condition(Shop.class);
        condition.or().andEqualTo("phone", phone);
        if (shopRepository.findByCondition(condition).isEmpty()) throw new ServiceException(ACCOUNT_NOT_OPEN);
    }


    public String findShopNameById(Integer shopId) {
        Shop shop = shopRepository.findById(shopId);
        if (shop == null) throw new ServiceException(SHOP_NOT_EXISTS);
        return shop.getName();
    }

    public String findShopUrlById(Integer shopId) {
        Shop shop = shopRepository.findById(shopId);
        if (shop == null) throw new ServiceException(SHOP_NOT_EXISTS);
        return shop.getCardimgurl();
    }


    public Shop findShopById(Integer shopId) {
        Shop shop = shopRepository.findById(shopId);
        if (shop == null) throw new ServiceException(SHOP_NOT_EXISTS);
        return shop;
    }


    public List<Shop> findByIds(List<Integer> shopIds) {
        Condition condition = new Condition(Shop.class);
        condition.or().andIn("id", shopIds);
        return shopRepository.findByCondition(condition);
    }

    public List<CustomerGroup> findGroupByIds(List<Integer> groupIds) {
        Condition condition = new Condition(CustomerGroup.class);
        condition.or().andIn("id", groupIds);
        return customerGroupRepository.findByCondition(condition);
    }


    public List<Shop> find(Boolean hasYKT) {
        Condition condition = new Condition(Shop.class);
        condition.or().andEqualTo("deleted", false)
                .andEqualTo("hasykt", hasYKT);
        return shopRepository.findByCondition(condition);
    }

    public List<Shop> findByName(Boolean hasYKT, String name) {
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(name.trim()) || name.length() < 2) {
            return new ArrayList<>();
        }

        Condition condition = new Condition(Shop.class);
        condition.or().andEqualTo("deleted", false)
                .andEqualTo("hasykt", hasYKT)
                .andLike("name", "%" + name + "%");
        return shopRepository.findByCondition(condition);
    }

    public List<Shop> find() {
        Condition condition = new Condition(Shop.class);
        condition.or().andEqualTo("deleted", false);
        return shopRepository.findByCondition(condition);
    }

    public List<Shop> findByName(String name) {
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(name.trim()) || name.length() < 2) {
            return new ArrayList<>();
        }


        Condition condition = new Condition(Shop.class);
        condition.or().andEqualTo("deleted", false)
                .andLike("name", "%" + name + "%");
        return shopRepository.findByCondition(condition);
    }

    public List<Shop> findAllShop() {
        return shopRepository.findAll();
    }

    public Shop getShopByPhone(String phone) {
        Condition condition = new Condition(Shop.class);
        condition.or().andEqualTo("phone", phone);
        List<Shop> shopList = shopRepository.findByCondition(condition);
        if (null == shopList || shopList.size() == 0) {
            return null;
        }
        return shopList.get(0);
    }

    public ShopCaogenyaoConfig getCaoGenYaoConfig(Integer shopId) {
        Condition condition = new Condition(ShopCaogenyaoConfig.class);
        condition.or().andEqualTo("shopId", shopId);
        List<ShopCaogenyaoConfig> shopCaogenyaoConfigList = shopCaogenyaoConfigRepository.findByCondition(condition);
        if (null == shopCaogenyaoConfigList || shopCaogenyaoConfigList.size() == 0) {
            throw new ServiceException("店铺信息尚未配置");
        }
        ShopCaogenyaoConfig shopCaogenyaoConfig = shopCaogenyaoConfigList.get(0);
        return shopCaogenyaoConfig;
    }

    public ShopAPIResult getAppMsg(String phone) {
        Shop shop = getShopByPhone(phone);
        if (shop == null) {
            return null;
        } else {
            ShopAPIResult result = new ShopAPIResult();
            result.setAppId(shop.getAppId());
            result.setAppSecret(shop.getSecurityKey());
            return result;
        }

    }


    public void createShopFromOpenAPI(ApiCreateShopForm form,
                                      ShopChannel shopChannel) {
        Shop shop = new Shop();
        Date date;
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR, 3);
        date = calendar.getTime();
        shop.setPhone(form.getPhone());
        shop.setName(form.getShopName());
        shop.setExpiretime(date);
        shop.setDeleted(false);
        shop.setCreated(new Date());
        shop.setSubAppid("000000000148982");
        shop.setSubMchId("1508590551");
        shop.setAliMchId("0bdb6c22638a1652e0662e9a96f8d47c");
        shop.setWxPayFunction(form.getIsRecharge());
        shop.setCardPayType(form.getIsYpCard());
        shop.setAllowUserRegistry(0);
        shop.setHasykt(false);
        shop.setIslocalimg(0);
        shop.setParentId(shopChannel.getId());
        shop.setApiServiceClassName(shopChannel.getChannelServiceClassName());
        shop.setTablewareType(shopMapper.getCountByTableware() + 1);
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String appSecret = uuid + System.currentTimeMillis();
        appSecret = MD5Util.MD5Lower32(appSecret);
        shop.setSecurityKey(appSecret);
        shopRepository.save(shop);
        String appId = "YunPeng20000000" + shop.getId();
        shop.setAppId(appId);
        shopRepository.update(shop);
        ProductCategory productCategory = new ProductCategory();
        productCategory.setName("全部");
        productCategory.setShopid(shop.getId());
        productCategory.setDeleted(false);
        productCategory.setType(new Byte("1"));
        productCategoryRepository.save(productCategory);
        Product product = new Product();
        product.setMinorcategoryid(productCategory.getId());
        product.setShopid(shop.getId());
        product.setUpdated(new Date());
        product.setCreated(new Date());
        product.setPrice(100L);
        product.setVipprice(100L);
        product.setSearchcode("-5");
        product.setName("自定义菜品");
        product.setStatus(new Byte("1"));
        product.setDeleted(false);
        productMapper.insertSelective(product);
        ShopConfigExtend shopConfigExtend = new ShopConfigExtend();
        shopConfigExtend.setShopId(shop.getId());
        shopConfigExtend.setAdvertRight(0);
        shopConfigExtendRepository.save(shopConfigExtend);
        Branch branch = new Branch();
        branch.setBranchName(shop.getName());
        branch.setShopId(shop.getId());
        branchMapper.insertSelective(branch);
        FaceHelperV3.createGroup(shop.getId().toString());
        Condition condition = new Condition(CmsRole.class);
        condition.or().andEqualTo("name", "ROLE_USER");
        List<CmsRole> cmsRoles = cmsRoleRepository.findByCondition(condition);
        if (cmsRoles != null && cmsRoles.size() > 0) {
            CmsRole cmsRole = cmsRoles.get(0);

            CmsSysUser cmsSysUser = new CmsSysUser();
            cmsSysUser.setPassword(MD5Util.MD5Lower32("000000"));
            cmsSysUser.setShopId(shop.getId());
            cmsSysUser.setUsername(shop.getPhone());
            cmsSysUser.setStatus(1);

            cmsSysUserRepository.save(cmsSysUser);

            cmsSysUserRoleMapper.insertRole(cmsSysUser.getId(), cmsRole.getId());
        }

        if (form.getIsReserve().equals(1)) {
            ShopOnlineMeal temp = new ShopOnlineMeal();
            temp.setShopEnabled(1);
            temp.setShopId(shop.getId());
            temp.setIsAutoConfig(1);
            temp.setAllowAdvanced(0);
            int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
            if (hour >= 10 && hour < 15) {
                temp.setBreakfastStatus(0);
                temp.setLunchStatus(1);
                temp.setDinnerStatus(0);
            } else if (hour >= 15) {
                temp.setBreakfastStatus(0);
                temp.setLunchStatus(0);
                temp.setDinnerStatus(1);
            } else {
                temp.setBreakfastStatus(1);
                temp.setLunchStatus(0);
                temp.setDinnerStatus(0);
            }
            shopOnlineMealMapper.insertSelective(temp);
        }
        if (form.getIsIdentify().equals(1)) {
            Condition urlCondition = new Condition(ShopBaiduUrl.class);
            urlCondition.or().andEqualTo("shopId", shop.getId());
            List<ShopBaiduUrl> shopBaiduUrlList = shopBaiduUrlRepository.findByCondition(urlCondition);

            if (null == shopBaiduUrlList || shopBaiduUrlList.size() == 0) {
                urlCondition.or().andEqualTo("used", 0);
                List<ShopBaiduUrl> baiduUrlList = shopBaiduUrlRepository.findByCondition(urlCondition);
                if (baiduUrlList != null && baiduUrlList.size() > 0) {
                    boolean urlType1Flag = false;
                    boolean urlType2Flag = false;
                    for (ShopBaiduUrl shopBaiduUrl : baiduUrlList) {
                        if (shopBaiduUrl.getUrlType() == 1 && urlType1Flag == false) {
                            shopBaiduUrl.setShopId(shop.getId());
                            shopBaiduUrl.setUsed(1);
                            shopBaiduUrlRepository.update(shopBaiduUrl);
                            urlType1Flag = true;
                        }
                        if (shopBaiduUrl.getUrlType() == 2 && urlType2Flag == false) {
                            shopBaiduUrl.setShopId(shop.getId());
                            shopBaiduUrl.setUsed(1);
                            shopBaiduUrlRepository.update(shopBaiduUrl);
                            urlType2Flag = true;
                        }
                    }

                    if (urlType2Flag && urlType1Flag) {
                        createAdminCustomer(shop);
                    }
                }
            }
        }
    }

    public void createAdminCustomer(Shop shop) {
        Condition condition = new Condition(CmsRole.class);
        condition.or().andEqualTo("name", "ROLE_Merchant_Admin");
        List<CmsRole> cmsRoles = cmsRoleRepository.findByCondition(condition);
        CmsRole cmsRole = cmsRoles.get(0);
        CmsSysUser cmsSysUser = new CmsSysUser();
        cmsSysUser.setPassword(MD5Util.MD5Lower32("000000"));
        cmsSysUser.setShopId(shop.getId());
        cmsSysUser.setUsername(shop.getPhone() + "admin");
        cmsSysUser.setStatus(1);
        cmsSysUserRepository.save(cmsSysUser);
        cmsSysUserRoleMapper.insertRole(cmsSysUser.getId(), cmsRole.getId());
    }

    public ShopChannel checkShopChannelNo(String channelNo) {
        Condition condition = new Condition(ShopChannel.class);
        condition.or().andEqualTo("channelNo", channelNo);

        List<ShopChannel> shopChannelList = shopChannelRepository.findByCondition(condition);

        if (shopChannelList != null && shopChannelList.size() > 0) {
            return shopChannelList.get(0);
        } else {
            throw new ServiceException("渠道号错误");
        }
    }

    public void saveShopTemp(ApiCreateShopForm form) {
        Condition condition = new Condition(ShopTemp.class);
        condition.or().andEqualTo("phone", form.getPhone())
                .andEqualTo("status",0);
        List<ShopTemp> shopTempList = shopTempRepository.findByCondition(condition);
        if (null == shopTempList || shopTempList.size() == 0) {
            ShopTemp shopTemp = new ShopTemp();
            shopTemp.setChannelNo(form.getChannelNo());
            shopTemp.setIsIdentify(form.getIsIdentify());
            shopTemp.setIsRecharge(form.getIsRecharge());
            shopTemp.setIsReserve(form.getIsReserve());
            shopTemp.setIsYpcard(form.getIsYpCard());
            shopTemp.setName(form.getShopName());
            shopTemp.setPhone(form.getPhone());
            shopTempRepository.save(shopTemp);
        } else {
            throw new ServiceException(SHOP_WAIT_EXISTS);
        }
    }

    public String getPostUrl(String channelNo) {

        Condition condition = new Condition(ShopChannel.class);

        condition.or().andEqualTo("channelNo", channelNo);

        ShopChannel shopChannel = shopChannelRepository.findByCondition(condition).get(0);

        return shopChannel.getChannelPostUrl();
    }


    public ShopConfigExtend getShopConfigExtend(Integer shopId) {
        Condition shopConfigCondition = new Condition(ShopConfigExtend.class);
        shopConfigCondition.or().andEqualTo("shopId", shopId)
                .andIsNull("branchId");

        List<ShopConfigExtend> configExtendList = shopConfigExtendRepository.findByCondition(shopConfigCondition);
        ShopConfigExtend shopConfigExtend = configExtendList.get(0);
        return shopConfigExtend;
    }

    public void shopReservePayConfig(Integer shopId,
                                     Integer reservePayConfig) {

        ShopConfigExtend extend = getShopConfigExtend(shopId);
        extend.setReservePayType(reservePayConfig);
        shopConfigExtendRepository.update(extend);
    }

    public void createShopPayCard(Shop shop,
                                  Customer customer,
                                  String cardNo,
                                  CustomerGroup customerGroup){
        PayCard payCard = PayCard.builder()
                .shopid(shop.getId())
                .customerid(customer.getId())
                .cardno(cardNo)
                .cardtype(CardType.BINGUO_CARD.getCode().byteValue())
                .deleted(false)
                .name(shop.getName() + "卡")
                .bzAccountbalance(0L)
                .wxAccountbalance(0L)
                .yktAccountbalance(0L)
                .accountbalance(0L)
                .ismaster(true)
                .isnopasswordpay(true)
                .build();

        payCardMapper.insertSelective(payCard);

        if (StringUtils.isEmpty(cardNo)) {
            PayCard tempPaycard = new PayCard();
            tempPaycard.setCardno(payCard.getId() + "");
            tempPaycard.setId(payCard.getId());

            payCardMapper.updateByPrimaryKeySelective(tempPaycard);
        }

        Condition customerExtendCondition = new Condition(CustomerExtend.class);
        customerExtendCondition.or().andEqualTo("customerId", customer.getId())
                .andEqualTo("shopId", shop.getId());

        List<CustomerExtend> customerExtendList =
                customerExtendMapper.selectByCondition(customerExtendCondition);

        if (customerExtendList != null && customerExtendList.size() > 0) {
            CustomerExtend customerExtend = customerExtendList.get(0);

            if (customerExtend.getIsAudit().intValue() == 0) {
                CustomerExtend temp = new CustomerExtend();
                temp.setId(customerExtend.getId());
                temp.setIsAudit(1);
                if (customerGroup != null){
                    temp.setGroupId(customerGroup.getId());
                    temp.setGroupName(customerGroup.getGroupName());
                }

                customerExtendMapper.updateByPrimaryKeySelective(temp);
            }
        }else {
            CustomerExtend customerExtend = new CustomerExtend();
            customerExtend.setShopId(shop.getId());
            customerExtend.setCustomerId(customer.getId());
            customerExtend.setIsAudit(1);
            customerExtend.setUserStatus(1);
            if (customerGroup != null){
                customerExtend.setGroupId(customerGroup.getId());
                customerExtend.setGroupName(customerGroup.getGroupName());
            }else {
                customerExtend.setGroupId(0);
                customerExtend.setGroupName("普通会员");
            }
            customerExtendMapper.insertSelective(customerExtend);
        }

    }

    public List<ShopConfig> getShopList(Integer shopId,
                                        Integer branchId,
                                        Integer deskId,
                                        String paramName){
        if (shopId == null){
            throw new ServiceException("店铺不存在");
        }

        if (StringUtils.hasText(paramName)){
            Condition condition;
            if (deskId != null){
                condition = new Condition(ShopConfig.class);
                condition.or().andEqualTo("dataStatus",1)
                        .andEqualTo("shopId",shopId)
                        .andEqualTo("paramName",paramName)
                        .andEqualTo("cashierDeskId",deskId);
            }else {
                condition = new Condition(ShopConfig.class);
                condition.or().andEqualTo("dataStatus",1)
                        .andEqualTo("shopId",shopId)
                        .andEqualTo("paramName",paramName)
                        .andEqualTo("cashierDeskId",0);
            }
            List<ShopConfig> configList = shopConfigRepository.findByCondition(condition);
            return configList;
        }else {
            Condition condition = new Condition(ShopConfig.class);
            condition.or().andEqualTo("dataStatus",1)
                    .andEqualTo("shopId",shopId)
                    .andEqualTo("cashierDeskId",0);
            List<ShopConfig> configList = shopConfigRepository.findByCondition(condition);
            if (deskId != null){
                condition = new Condition(ShopConfig.class);
                condition.or().andEqualTo("dataStatus",1)
                        .andEqualTo("shopId",shopId)
                        .andEqualTo("cashierDeskId",deskId);
                List<ShopConfig> deskConfigList = shopConfigRepository.findByCondition(condition);
                List<ShopConfig> resultConfigList = configList;
                for (ShopConfig config : deskConfigList){
                    for (int i = 0; i < configList.size();i++){
                        if (config.getParamName().equals(configList.get(i).getParamName())){
                            resultConfigList.set(i,config);
                            break;
                        }
                        if (i == (configList.size()- 1)){
                            resultConfigList.add(config);
                        }
                    }
                }
                return resultConfigList;
            }else {
                return configList;
            }
        }
    }


    public JSONObject checkChannelShop(String phone,
                                       ShopChannel shopChannel){
        JSONObject result = new JSONObject();

        Shop shop = getShopByPhone(phone);

        if (shop == null){
            throw new ServiceException("不存在该商户");
        }else {
            if (shop.getParentId().equals(shopChannel.getId())){
                result.put("appId",shop.getAppId());
                result.put("appSecret",shop.getSecurityKey());
                result.put("phone",shop.getPhone());
                result.put("id",shop.getId());
                return result;
            }else {
                throw new ServiceException("非该渠道号创建的商户");
            }
        }
    }

    public Shop getShopByAppId(String appId){

        Condition condition = new Condition(Shop.class);

        condition.or().andEqualTo("appId",appId);

        List<Shop> shopList = shopRepository.findByCondition(condition);

        if(shopList == null || shopList.size() == 0){
            return null;
        }else {
            return shopList.get(0);
        }
    }

}

